package gwt.immunology.server.service;

import gwt.immunology.client.service.UserService;
import gwt.immunology.server.converter.UserDtoConverter;
import gwt.immunology.shared.GenericDto;
import gwt.immunology.shared.ResultSetDto;

import java.util.List;

import models.User;
import play.Logger;
import play.modules.gwt2.GWT2Service;
import play.modules.gwt2.GWT2ServicePath;

@GWT2ServicePath("/immunology/user")
public class UserServiceImpl extends GWT2Service implements UserService {

    @Override
    public GenericDto registerNewUser(GenericDto userDto) {
	GenericDto result = null;
	if (userDto != null && !userDto.isEmpty()) {
	    User user = UserDtoConverter.convertGenericDtoToUser(userDto);
	    Logger.info("registering new user");
	    user = User.em().merge(user);
	    result = UserDtoConverter.convertUserToGenericDto(user);
	} else {
	    Logger.warn("can't register user with null value");
	}
	return result;
    }

    @Override
    public void deleteUserById(Long userId) {
	if (userId != null) {
	    User user = User.em().find(User.class, userId);
	    if (user != null) {
		Logger.info("deleting user by id = " + userId);
		User.em().remove(user);
	    } else {
		Logger.warn("can't delete user with null value");
	    }
	} else {
	    Logger.warn("can't delete user by id = " + userId);
	}
    }

    @Override
    public GenericDto getUserById(Long userId) {
	GenericDto result = null;
	if (userId != null) {
	    Logger.info("retrieving user by id = " + userId);
	    User user = User.em().find(User.class, userId);
	    result = UserDtoConverter.convertUserToGenericDto(user);
	} else {
	    Logger.warn("can't retrieve user by id = " + userId);
	}
	return result;
    }

    @Override
    public GenericDto editUser(GenericDto userDto) {
	GenericDto result = null;
	if (userDto != null && !userDto.isEmpty()) {
	    User user = UserDtoConverter.convertGenericDtoToUser(userDto);
	    Logger.info("editing user with id = " + user.userId);
	    user = User.em().merge(user);
	    result = UserDtoConverter.convertUserToGenericDto(user);
	} else {
	    Logger.warn("can't edit user with null value");
	}
	return result;
    }

    @Override
    public ResultSetDto getAllUsers() {
	ResultSetDto result = null;
	Logger.info("retrieving all users");
	List<User> users = User.all().fetch();
	result = UserDtoConverter.convertUsersToResultSetDto(users);
	return result;
    }

}
